package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.dto.ArticleDto;
import com.heima.article.dto.ArticleHomeDto;
import com.heima.article.dto.ArticleInfoDto;
import com.heima.article.dto.ArticleStreamMessage;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.task.ArticleHtmlTasks;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 文章信息表，存储已发布的文章 服务实现类
 *
 * @author syl
 * @since 2022-06-29
 */
@Slf4j
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {

    @Autowired
    private IApArticleContentService apArticleContentService;

    @Autowired
    private ArticleHtmlTasks articleHtmlTasks;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public ResponseResult<Long> saveApArticle(ArticleDto dto) {
        if (dto.getId() == null) {
            ApArticle apArticle = new ApArticle();
            BeanUtils.copyProperties(dto, apArticle);
            apArticle.setCreatedTime(new Date());
            this.save(apArticle);
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            apArticleContentService.save(apArticleContent);
            articleHtmlTasks.createArticleHtml(apArticle, dto.getContent());
            return ResponseResult.okResult(apArticle.getId());
        } else {
            ApArticle apArticle = new ApArticle();
            BeanUtils.copyProperties(dto, apArticle);
            apArticle.setCreatedTime(new Date());
            this.updateById(apArticle);
            LambdaUpdateWrapper<ApArticleContent> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(ApArticleContent::getContent, dto.getContent());
            updateWrapper.eq(ApArticleContent::getArticleId, dto.getId());
            apArticleContentService.update(updateWrapper);
            articleHtmlTasks.createArticleHtml(apArticle, dto.getContent());
            return ResponseResult.okResult(apArticle.getId());
        }
    }

    @Override
    public ResponseResult load(ArticleHomeDto dto, int type) {
        if (dto.getLoaddir() == 1) {
            String key = "hot_article_first_page" + dto.getChannelId();
            long start = 0;
            long end = dto.getSize() - 1;
            Set<String> strings = redisTemplate.boundZSetOps(key).reverseRange(start, end);
            List<ApArticle> list = new ArrayList<>();
            for (String string : strings) {
                ApArticle apArticle = JSON.parseObject(string, ApArticle.class);
                list.add(apArticle);
            }
            if (list.size() >= dto.getSize()) {
                return ResponseResult.okResult(list);
            }
        }
        LambdaQueryWrapper<ApArticle> queryWrapper = new LambdaQueryWrapper<>();
        if (dto.getChannelId() != 0) {
            queryWrapper.eq(ApArticle::getChannelId, dto.getChannelId());
        }
        if (type == 0) {
            queryWrapper.gt(ApArticle::getPublishTime, dto.getMaxTime());
        } else {
            queryWrapper.lt(ApArticle::getPublishTime, dto.getMinTime());
        }
        queryWrapper.eq(ApArticle::getIsDelete, false);
        queryWrapper.eq(ApArticle::getIsDown, false);
        queryWrapper.orderByDesc(ApArticle::getPublishTime);
        Page<ApArticle> page = new Page<>(1, dto.getSize());
        Page<ApArticle> page1 = this.page(page, queryWrapper);
        return ResponseResult.okResult(page1.getRecords());
    }

    @Override
    public ResponseResult loadArticleInfo(ArticleInfoDto dto) {

        ApArticle apArticle = this.getById(dto.getArticleId());
        if (apArticle == null || apArticle.getIsDelete() || apArticle.getIsDown()) {
            log.info("查不到数据，文章id是：" + dto.getArticleId());
            ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        LambdaQueryWrapper<ApArticleContent> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApArticleContent::getArticleId, dto.getArticleId());
        ApArticleContent articleContent = apArticleContentService.getOne(queryWrapper);
        Map resultMap = new HashMap<>();
        resultMap.put("config", apArticle);
        resultMap.put("content", articleContent);
        return ResponseResult.okResult(resultMap);
    }

    @Override
    public void compute() {//计算热点文章，放入redis中
        Date beforeDate = DateTime.now().minusDays(300).toDate();
        LambdaQueryWrapper<ApArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApArticle::getIsDown, false);
        queryWrapper.eq(ApArticle::getIsDelete, false);
        queryWrapper.gt(ApArticle::getPublishTime, beforeDate);
        List<ApArticle> list = this.list(queryWrapper);
        //计算每个文章的分值
        for (ApArticle apArticle : list) {
            Integer score = computeScore(apArticle);
            ApArticle cache = new ApArticle();
            cache.setId(apArticle.getId());
            cache.setTitle(apArticle.getTitle());
            cache.setAuthorId(apArticle.getAuthorId());
            cache.setAuthorName(apArticle.getAuthorName());
            cache.setLayout(apArticle.getLayout());
            cache.setImages(apArticle.getImages());
            cache.setStaticUrl(apArticle.getStaticUrl());
            cache.setPublishTime(apArticle.getPublishTime());
            redisTemplate.boundZSetOps("hot_article_first_page_" + apArticle.getChannelId()).add(JSON.toJSONString(apArticle), score);
            redisTemplate.boundZSetOps("hot_article_first_page_0").add(JSON.toJSONString(apArticle), score);
        }
    }

    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;
        if (apArticle.getViews() != null) {
            score += apArticle.getViews() * 1;
        }
        if (apArticle.getLikes() != null) {
            score += apArticle.getLikes() * 3;
        }
        if (apArticle.getComment() != null) {
            score += apArticle.getComment() * 5;
        }
        if (apArticle.getCollection() != null) {
            score += apArticle.getCollection() * 8;
        }
        return score;
    }

    @Override
    public void updateHotArticle(ArticleStreamMessage articleStreamMessage) {
        //重新计算文章的热度值（今天产生的数据*3）
        Long articleId = articleStreamMessage.getArticleId();
        ApArticle apArticle = this.getById(articleId);
        ApArticle cache = new ApArticle();
        cache.setId(apArticle.getId());
        cache.setTitle(apArticle.getTitle());
        cache.setAuthorId(apArticle.getAuthorId());
        cache.setAuthorName(apArticle.getAuthorName());
        cache.setLayout(apArticle.getLayout());
        cache.setImages(apArticle.getImages());
        cache.setStaticUrl(apArticle.getStaticUrl());
        cache.setPublishTime(apArticle.getPublishTime());
        //更新redis中的数据
        //String key = "hot_article_first_page_" + dto.getChannelId();
        Double score = redisTemplate.boundZSetOps("hot_article_first_page_" + apArticle.getChannelId()).score(JSON.toJSONString(cache));
        Integer todayScore = getTodayScore(articleStreamMessage);
        if (score != null) {
            redisTemplate.boundZSetOps("hot_article_first_page_" + apArticle.getChannelId()).add(JSON.toJSONString(cache),score+todayScore);
            redisTemplate.boundZSetOps("hot_article_first_page_0").add(JSON.toJSONString(cache),score+todayScore);
        } else {
            redisTemplate.boundZSetOps("hot_article_first_page_" + apArticle.getChannelId()).add(JSON.toJSONString(cache),todayScore);
            redisTemplate.boundZSetOps("hot_article_first_page_0").add(JSON.toJSONString(cache),todayScore);
        }
        //更新mysql中ApArticle中的阅读数、点赞数、评论数、收藏数
        LambdaUpdateWrapper<ApArticle> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ApArticle::getId, articleId);
        updateWrapper.setSql("views=views+" + articleStreamMessage.getView());
        updateWrapper.setSql("likes=likes+" + articleStreamMessage.getLike());
        updateWrapper.setSql("comment=comment+" + articleStreamMessage.getComment());
        updateWrapper.setSql("collection=collection+" + articleStreamMessage.getCollect());
        this.update(updateWrapper);
    }

    private Integer getTodayScore(ArticleStreamMessage articleStreamMessage) {
        Long score = (articleStreamMessage.getView() * 1 + articleStreamMessage.getLike() * 3 + articleStreamMessage.getComment() * 5 + articleStreamMessage.getCollect() * 8)*3;
        return score.intValue();
    }
}
